package com.iretailer.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by xjw on 2017/8/20.
 * 统一的 http 日志处理
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger log = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.iretailer.web.*.*(..))")
    public void log() {
    }

    /**
     * 请求
     * @param joinPoint
     */

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.debug("url={}",request.getRequestURL());
        log.debug("method={}",request.getMethod());
        log.debug("ip={}",request.getRemoteAddr());
        log.debug("clss_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        log.debug("args={}",joinPoint.getArgs());

    }

    @After("log()")
    public void doAfter() {
    }

    @AfterReturning(returning = "object" ,pointcut = "log()")
    public void doAfterReturning(Object object){
        log.debug("response={}", JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect));

    }

}
